package com.carlinfo.usercenter.common.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.carlinfo.usercenter.common.util.RegexUtil;
import com.carlinfo.usercenter.common.util.VerifyCodeUtil;
/**
 * 放的是所有的公共代码 
 * @author jjh
 *
 */
public class CommonServlet extends HttpServlet
{
	private RegexUtil regexUtil = new RegexUtil();
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		System.out.println("===CommonServlet===service==");
		String method = request.getParameter("method");
		if("code".equalsIgnoreCase(method))
		{
			/* 验证码 */
			this.code(request,response);
		}
	}

	/**
	 * 生成一个验证码 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void code(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		response.setHeader("Pragma", "No-cache");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expires", 0);  
        response.setContentType("image/jpeg");  
          
        //生成随机字串  
        /*String verifyCode = VerifyCodeUtil.generateVerifyCode(4);  */
        /* 使用自己的类,生成验证码 */
        String verifyCode = this.regexUtil.randString(4);
        //存入会话session  
        HttpSession session = request.getSession(true);  
        /* 将图片中的验证码放到了session中 */
        session.setAttribute("randSess", verifyCode);  
        //生成图片  
        int w = 100, h = 40;  
        VerifyCodeUtil.outputImage(w, h, response.getOutputStream(), verifyCode); 
	}
	
}
